<template>
  <view class="page">
    <view v-if="!showDownload" class="container">
      <view class="tit">生成头像</view>
      <view class="small-tit">生成类型</view>
      <view class="selected" @click="showSelect">{{ selectType }}</view>
      <view class="small-tit">生辰八字</view>
      <tui-input v-model="bazi" :radius="10"
                 :size="24"
                 backgroundColor="#f2f3f5"
                 inputBorder padding="20rpx" placeholder="生辰八字" style="margin: 10rpx 0"></tui-input>
      <tui-select :list="list" :show="show" btnBackground="#C89F62" checkboxColor="#C89F62" @close="onClose"
                  @confirm="confirm"></tui-select>
      <view class="small-tit">生成描述</view>
      <view class="text-box">
        <tui-textarea
            v-model="describeCn"
            :border-bottom="false"
            :borderTop="false"
            :radius="10"
            :size="24"
            backgroundColor="#f2f3f5"
            padding="20rpx"
            placeholder="请输入内容"></tui-textarea>
      </view>
      <tui-form-button
          v-if="describe.length === 0"
          :disabled="btnLoading"
          :loading="btnLoading" :size="26"
          background="#C89F62"
          btnSize="medium"
          radius="50px"
          style="margin:10rpx auto"
          @click="generateDescribe"
      >
        生成描述
      </tui-form-button>
      <tui-form-button
          v-else
          :disabled="btnLoading"
          :loading="btnLoading" :size="26"
          background="#C89F62"
          btnSize="medium"
          radius="50px"
          style="margin:10rpx auto"
          @click="generateAvatar"
      >
        生成头像
      </tui-form-button>
    </view>

    <view v-if="showDownload" class="container">
      <image :src="imgUrl" class="sourceImage" mode="widthFix"></image>
      <tui-form-button
          :size="26"
          background="#C89F62"
          btnSize="medium"
          radius="50px"
          style="margin:10rpx auto"
          @click="saveimg(imgUrl)"
      >
        保存
      </tui-form-button>
    </view>
  </view>
</template>
<script>
import {commonStorage} from "../../utils/common";
import {userInfoApi} from "../../apis/user";
import {yfgpaipanApi} from "../../apis/qiuqian";
import TuiInput from "../../components/thorui/tui-input/tui-input.vue";

export default {
  name: "generateAvatar",
  components: {TuiInput},
  data() {
    return {
      describe: '',
      describeCn: '',
      describeEn: '',
      userInfo: {},
      userInputInfo: {},
      btnLoading: false,
      chatList: [],
      imgUrl: '',//https://platform.cdn.zhishuyun.com/midjourney/3611358e-1818-4523-a040-f318ca15ea5b.png
      imgConfig: {},
      showDownload: false,
      show: false,
      list: [
        {
          text: '动物',
          value: '动物',
          checked: true
        },
        {
          text: '风景',
          value: '风景'
        },
        {
          text: '人物',
          value: '人物'
        },
        {
          text: '卡通',
          value: '卡通'
        },
        {
          text: '写实',
          value: '写实'
        },
        {
          text: '3d',
          value: '3d'
        },
      ],
      selectType: '动物',
      bazi: '',

    };
  },
  onLoad() {
    this.getUserInfo();
  },
  methods: {
    showSelect() {
      this.show = true
    },
    confirm(e) {
      console.log(e)
      this.selectType = e.options.value
      this.onClose()
    },
    onClose() {
      this.show = false
    },
    saveimg(url, tip = true) {
      let platform = uni.getSystemInfoSync().uniPlatform
      if (platform == 'web') {
        const link = document.createElement('a');
        link.href = url;
        link.download = 'downloaded-image.jpg';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        return

        function downloadH5(base64) {
          var arr = base64.split(",");
          var bytes = atob(arr[1]);
          var ab = new ArrayBuffer(bytes.length);
          var ia = new Uint8Array(ab);
          for (var i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
          }
          var blob = new Blob([ab], {
            type: "application/octet-stream"
          });
          var url = URL.createObjectURL(blob);
          var a = document.createElement("a");
          a.href = url;
          a.download = new Date().valueOf() + ".png";
          var e = document.createEvent("MouseEvents");
          e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
          a.dispatchEvent(e);
          URL.revokeObjectURL(url);
          if (tip) {
            uni.showToast({
              title: "下载完成",
              icon: "none"
            });
          }

        }

        return downloadH5(url)
      }

      if (platform == 'mp-weixin') {
        uni.saveImageToPhotosAlbum({
          filePath: url,
          success() {
            if (tip) {
              uni.showToast({
                title: "已保存 请至相册查看",
                icon: "none"
              });
              uni.vibrateShort({});
            }

          },
          fail(res) {
            if (res.errMsg.indexOf("fail") && res.errMsg.indexOf("cancel") == -1) {
              uni.showModal({
                title: "您需要授权相册才可以保存~",
                success(res) {
                  if (res.confirm) {
                    uni.openSetting();
                  }
                }
              });
            }
          }
        });
      }
    },
    generateAvatar() {
      this.btnLoading = true;
      fetch('https://api.zhishuyun.com/midjourney/imagine?token=30721f0b46234ec3a8be845a41fb360e', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          prompt: this.describeCn,
          translation: true
        })
      }).then(res => res.json()).then((data) => {
        this.imgUrl = data.raw_image_url;
        this.showDownload = true;
        this.imgConfig = data
      }).finally(() => {
        this.btnLoading = false;
      });
    },
    async getUserInfo() {
      this.btnLoading = true;
      let loginInfo =
          commonStorage.getStorageSync("userInfo") &&
          JSON.parse(commonStorage.getStorageSync("userInfo"));
      if (loginInfo) {
        let {code, data} = await userInfoApi(loginInfo.userId);
        if (code == 1) {
          this.userInfo = data;
          // let sex = data.gender == 1 ? "男" : "女";
          this.baziInfo();
          if (this.userInfo.birthDate) {
            this.bazi = `${this.userInfo.dataType === 'solar' ? '阳历' : '阴历'} ${this.userInfo.birthDate}`
          }
          // let query = `我的名字叫${data.userName},性别为${sex}，出生地点为${data.birthPlace},出生时间为${data.birthDate}`;
          // this.userInputInfo = query;
        } else {
          this.btnLoading = false;
        }

      }
    },
    extractEnclosedText(text) {
      // 匹配被 [] 包裹的内容
      const bracketRegex = /\[(.*?)\]/g;
      // 匹配被 ``` ``` 包裹的内容
      const backtickRegex = /```(.*?)```/g;

      let bracketMatches = [];
      let backtickMatches = [];

      let match;
      // 提取被 [] 包裹的内容
      while ((match = bracketRegex.exec(text)) !== null) {
        bracketMatches.push(match[1]);
      }

      // 提取被 ``` ``` 包裹的内容
      while ((match = backtickRegex.exec(text)) !== null) {
        backtickMatches.push(match[1]);
      }

      return {
        bracketTexts: bracketMatches,
        backtickTexts: backtickMatches
      };
    },
    async baziInfo() {
      let arrs = JSON.parse(JSON.stringify(this.userInfo.birthDate));
      let arr2 = arrs.split(" ")[0];
      let {code, data} = await yfgpaipanApi({
        name: this.userInfo.userName,
        sex: this.userInfo.gender,
        type: 1,
        year: arr2.split("-")[0],
        month: parseInt(arr2.split("-")[1]),
        day: parseInt(arr2.split("-")[2]),
        hours: 12,
        minute: 0,
        sect: 1,
        zhen: 2
      });
      if (code == 1 && data.baziInfo) {
        let query = `【${arr2.split("-")[0]}.${arr2.split("-")[1]}.${
            arr2.split("-")[2]
        } 年柱：${data.baziInfo.bazi[0]} 月柱：${data.baziInfo.bazi[1]} 日柱：${
            data.baziInfo.bazi[2]
        } 时柱：${data.baziInfo.bazi[3]}】`;
        this.userInputInfo = query;
      }
      this.btnLoading = false;
    },
    generateDescribe() {
      let _this = this;
      _this.chatList.push({
        role: "user",
        content: `${this.bazi} 生成${_this.selectType}风格的描述`,
        "content_type": "text"
      });
      this.btnLoading = true;
      fetch('https://api.coze.cn/v3/chat', {
        method: 'POST',
        headers: {
          "Content-Type": "application/json",
          Connection: "keep-alive",
          Authorization: 'Bearer pat_KgjuEwQGxZtbEYdryO2N1R48EJOZYM7XWhFORvvkIRrMcjNKoDgJo56WF6FsH0Vf',//`Bearer ${this.apiKey}`,
          Accept: "*/*"
        },
        body: JSON.stringify({
          bot_id: "7424478657823211571",
          user_id: _this.userInfo.userId,
          query: `${_this.userInputInfo},${this.bazi} 生成${_this.selectType}风格的描述`,
          stream: true,
          additional_messages: _this.chatList,
          auto_save_history: true,
        })
      }).then(response => {
        if (response.body) {

          return response.body;
        }
        return response.text();
      }).then(data => {
        // 处理流式数据
        if (data instanceof ReadableStream) {
          const reader = data.getReader();

          function read() {
            reader.read().then(({done, value}) => {
              if (done) {
                console.log('Stream complete');
                _this.btnLoading = false;
                _this.describeCn = _this.extractEnclosedText(JSON.stringify(_this.describe)).bracketTexts[0];
                _this.describeEn = _this.extractEnclosedText(JSON.stringify(_this.describe)).backtickTexts[0];
                console.log(JSON.stringify(_this.describe))

                return;
              }
              const chunk = new TextDecoder().decode(value, {stream: true});
              let reader = chunk
              if (reader === 'data:{"event":"done"}') {

                return;
              }
              if (reader.search('event:conversation.message.delta') !== -1) {
                console.log(reader)
                reader = reader.replaceAll("data:", "");
                reader = reader.split(/[(\r\n)\r\n]+/);
                reader.forEach(item => {
                  if (item) {
                    try {
                      item = JSON.parse(item);
                      if (item.type == "answer") {
                        let text = item.content;

                        _this.describe += text;
                      }
                    } catch (e) {

                    }
                  }
                })

              }
              // console.log(reader)
              // if (reader[0] && reader[0] === "event:conversation.message.delta") {
              // }


              read();
            }).catch(err => {
              console.error('Stream reading error:', err);
            });
          }

          read();
        } else {
          console.log(data);
        }
      })
          .catch(error => console.error('Error:', error))

    }


  },
}
</script>
<style lang="scss" scoped>
.page, page {
  min-height: 100vh;
  background-color: #f2f3f5;
}

.container {
  width: 700rpx;
  margin: 50rpx auto;
  padding: 40rpx;
  border-radius: 20rpx;
  background: #ffffff;
  box-shadow: 41rpx 41rpx 82rpx #e6e6e6,
  -41rpx -41rpx 82rpx #ffffff;
  box-sizing: border-box;

  .tit {
    font-size: 30rpx;
    font-weight: 500;
    text-align: center;
  }

  .small-tit {
    font-size: 26rpx;
    font-weight: 500;
  }

  .line {
    height: 1rpx;
    background-color: #E9E9E9;
    margin: 10rpx 0;
  }

  .text-box {
    padding: 10rpx 0;
  }

  .sourceImage {
    width: 100%;
  }
}

.selected {
  padding: 10rpx;
  border: 1px solid #dedede;
  font-weight: normal;
  border-radius: 5px;
  font-size: 28rpx;
  color: #999;
  margin: 10rpx 0;
}
</style>
